package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"git.tmuyu.com.cn/beego/models"
	"git.tmuyu.com.cn/beego/util"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/toolbox"
	"io/ioutil"
	"net/http"
	"strings"
)

//获取wx_AccessToken 拼接get请求 解析返回json结果 返回 AccessToken和err
func FetchAccessToken(appID, appSecret, accessTokenFetchUrl string) (string, error) {
	if appID == "" {
		logs.Error("appID为空")
		return "", nil
	}
	if appSecret == "" {
		logs.Error("appSecret为空")
		return "", nil
	}
	requestLine := strings.Join([]string{accessTokenFetchUrl,
		"?grant_type=client_credential&appid=",
		appID,
		"&secret=",
		appSecret}, "")

	resp, err := http.Get(requestLine)
	if err != nil || resp.StatusCode != http.StatusOK {
		fmt.Println("发送get请求获取 atoken 错误", err)
		logs.Error("发送get请求获取 atoken 错误", err)
		return "", err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("发送get请求获取 atoken 读取返回body错误", err)
		logs.Error("发送get请求获取 atoken 读取返回body错误", err)
		return "", err
	}

	if bytes.Contains(body, []byte("access_token")) {
		atr := models.AccessTokenResponse{}
		err = json.Unmarshal(body, &atr)
		if err != nil {
			fmt.Println("发送get请求获取 atoken 返回数据json解析错误", err)
			logs.Error("发送get请求获取 atoken 返回数据json解析错误", err)
			return "", err
		}
		return atr.AccessToken, nil
	} else {
		fmt.Println("发送get请求获取 微信返回 err")
		ater := models.AccessTokenErrorResponse{}
		err = json.Unmarshal(body, &ater)
		fmt.Printf("发送get请求获取 微信返回 的错误信息 %+v\n", ater)
		if err != nil {
			return "", err
		}
		return "", fmt.Errorf("%s", ater.Errmsg)
	}
}

//存取更新access_token
func GetAndUpdateDBWxAToken() (token string, err error) {

	var wxBase models.WxBase
	var AccessToken string
	wxBase.AppID = beego.AppConfig.String("appID")
	logs.Info("appID", wxBase.AppID)

	wxBase.AppSecret = beego.AppConfig.String("appSecret")
	logs.Info("AppSecret", wxBase.AppSecret)
	AccessToken = string(util.GetRedis("access_token"))

	if AccessToken == "" {
		//向微信服务器发送获取accessToken的get请求
		logs.Info("发送请求去接收token")
		AccessToken, err = FetchAccessToken(wxBase.AppID, wxBase.AppSecret, "https://api.weixin.qq.com/cgi-bin/token")
		if err != nil {
			logs.Error("向微信服务器发送获取accessToken的get请求失败", err)
			return "", err
		}
		util.SetRedis("access_token", AccessToken, true, 7100)
	} else {
		logs.Info("redis获取", AccessToken)
	}

	return AccessToken, nil
}

func ShopTimeTask() {
	timeStr2 := "0 */60 * * * *" // 获取wx token
	t2 := toolbox.NewTask("getAtoken", timeStr2, func() error {

		_, err := GetAndUpdateDBWxAToken()
		if err != nil {
			//todo 向微信请求access_token失败 结合业务逻辑处理

			return err
		}
		return nil
	})
	toolbox.AddTask("tk2", t2)
	toolbox.StartTask()

}
